package base.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * ResponseUtil:
 *
 * @author 姜治昊
 * @time 2017年11月4日 上午12:24:07
 */
public class ResponseUtil {
	/**
	 *  ajax发送消息
	 */  
	public static void write(HttpServletResponse response,Object o){
		response.setContentType("text/html;charset=utf-8");
		if(o != null){
			try{
				PrintWriter out=response.getWriter();
				out.print(o.toString());
				out.flush();
				out.close();
			}catch(Exception e){
				e.printStackTrace();
			}finally{}
		}else{
		}
	}

	/**
	 *  下載文件
	 * @param response 請求
	 * @param filepath 文件路徑
	 * @param outfileName 下載到什麼位置
	 * @param delete 刪除文件
	 * @throws IOException io異常
	 */
	public static void downloadfile(HttpServletResponse response,String filepath,String outfileName, Boolean delete) throws IOException {
		FileInputStream f = new FileInputStream(filepath);
		//讀取文件f中沒有讀的字節，定義好要用的內存
		byte[] fb = new byte[f.available()];
		//開始讀文件fb
		f.read(fb); 
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(outfileName.getBytes("gb2312"),
						"iso8859-1"));
		ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		//邊讀邊寫
		int b;
		while ((b = bais.read()) != -1) {
			response.getOutputStream().write(b);
		}
		response.getOutputStream().flush();//讓輸出瀏刷新，將數據輸出
		f.close();
		if(delete){
			File exeFile = new File(filepath);
			exeFile.delete();
		}
	}
}
